import { _decorator, Component, Node, CCFloat, Collider, ICollisionEvent, Vec3, ForwardFlow, math } from 'cc';
import { Events } from '../events/Events';
import { MathUtil } from '../utils/MathUtil';
import { ProjectileProperty } from './ProjectileProperty';
const { ccclass, property } = _decorator;

let tempPosition = new Vec3()
let forward = new Vec3()
@ccclass('Projectile')
export class Projectile extends Component {
    @property(CCFloat)
    private linearSpeed: number = 3
    @property(CCFloat)
    private angularSpeed: number = 180
    public host: Node = null
    private target: Node = null
    private projectileProperty: ProjectileProperty = new ProjectileProperty()
    private collider: Collider = null

    public startTime = 0
    start() {
        this.collider = this.node.getComponent(Collider)
        this.collider.on("onTriggerEnter", this.onTriggerEnter, this)
    }

    update(deltaTime: number) {
        this.startTime += deltaTime
        if (this.startTime > this.projectileProperty.lifeTime) {
            this.node.emit(Events.OnPrejectileDead, this)
            return
        }

        //跟踪
        if (this.target !== null) {
            Vec3.subtract(tempPosition, this.target.worldPosition, this.node.worldPosition)
            tempPosition.normalize()
            const angle = math.toRadian(this.angularSpeed) * deltaTime
            MathUtil.rotateToWorld(forward, this.node.worldPosition, tempPosition, angle)
        }

        //移动
        Vec3.scaleAndAdd(tempPosition, this.node.worldPosition, this.node.forward, this.linearSpeed * deltaTime)
        this.node.worldPosition = tempPosition
    }
    onDestory() {

    }
    private onTriggerEnter(event: ICollisionEvent) {
        // this.node.emit(Events.OnPrejectileDead, this)
    }
}
